//
//  DPBlock.m
//  HigherOrderMessaging
//
//  Created by Ofri Wolfus on 16/12/06.
//  Copyright 2006 Ofri Wolfus. All rights reserved.
//

#import "DPBlock.h"


static /*__thread*/ void *__current_block_content;

void _dp_block_execute(id self, ...) {
	goto *__current_block_content;
	//asm volatile ("b %0" : "=m" (*__current_block_content));
}

void _dp_block_finish(id self, ...) {
	return;
}

const void *__dp_block_finish = _dp_block_finish;

@implementation DPBlock

- (id)initWithBlockLocation:(void *)loc frame:(void *)frame length:(unsigned)length {
	if ((self = [super init])) {
		_block_start = loc;
		_frame = frame;
		_frame_length = length;
		info = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
										 &kCFTypeDictionaryKeyCallBacks,
										 NULL);
	}
	
	return self;
}

- (void)dealloc {
	CFRelease(info);
	[super dealloc];
}

- (id)process {
	__current_block_content = _block_start;
	__builtin_return(__builtin_apply(_dp_block_execute, _frame, _frame_length));
}

- (void)setValue:(void *)val forKey:(id)key {
	CFDictionarySetValue(info, val, key);
}

- (void *)valueForKey:(id)key {
	return (void *)CFDictionaryGetValue(info, key);
}

@end

id DPCreateBlock(void *location, void *frame, unsigned frame_length) {
	return [[[DPBlock alloc] initWithBlockLocation:location
											 frame:frame
											length:frame_length] autorelease];
}
